//
//  SCComposeViewController.swift
//  weibo
//
//  Created by 阿城 on 15/12/13.
//  Copyright © 2015年 阿城. All rights reserved.
//

import UIKit
import SVProgressHUD

class SCComposeViewController: UIViewController {

    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        // Do any additional setup after loading the view.
    }
    
    
    private func setupNavBar(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: "leftBarButtonClick")
        navigationItem.rightBarButtonItem = rightBarItem
        navigationItem.rightBarButtonItem?.enabled = false
        
        //方法1
        //navigationItem.titleView = titleview
        
        //方法2
        let name = SCUserInfoViewModel.shareInfoViewModel.userInfoMod?.screen_name ?? ""
        let attributeTitle = NSMutableAttributedString(string: "发微博\n\(name)")
        
        let totalAttrs = [
            NSFontAttributeName: UIFont.systemFontOfSize(12),
            NSForegroundColorAttributeName: UIColor.darkGrayColor()
            
        ]
        attributeTitle.addAttributes(totalAttrs, range: NSRange(location: 0, length: attributeTitle.string.characters.count))
        
        let subAttrs = [
            NSFontAttributeName: UIFont.systemFontOfSize(15),
            NSForegroundColorAttributeName: UIColor.blackColor(),
        ]
        attributeTitle.addAttributes(subAttrs, range: NSRange(location: 0, length: 3))
        
        let lab = UILabel()
        lab.attributedText = attributeTitle
        lab.textAlignment = .Center
        lab.numberOfLines = 0
        lab.sizeToFit()
        navigationItem.titleView = lab
    }

    private func setupUI(){
        view.backgroundColor = UIColor.whiteColor()
        setupNavBar()
        
        //监听通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "emoticonNotificationDeal:", name: kEmoticonNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "deleteNotificationDeal", name: kDeleteNotification, object: nil)
        
        //设置输入框
        view.addSubview(textView)
        textView.alwaysBounceVertical = true
        textView.placeholder = "听说晴天,雨鞋与棉袄更配哦"
        textView.font = UIFont.systemFontOfSize(20)
        textView.delegate = self
//        textView.backgroundColor = UIColor.redColor()
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view).offset(10)
            make.leading.equalTo(view).offset(10)
            make.trailing.equalTo(view).offset(-10)
            make.height.equalTo(600)
        }
        
        //设置照片选择框
        textView.addSubview(photoPicker)
//        photoPicker.backgroundColor = UIColor.grayColor()
        photoPicker.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(80)
            make.centerX.equalTo(textView)
            make.leading.equalTo(textView)
            make.height.equalTo(photoPicker.snp_width)
        }
        photoPicker.addImageBackclosrue = {
            self.selectPhoto()
        }
        
        //添加底部工具栏
        view.addSubview(bar)
        bar.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(view)
            make.trailing.equalTo(view)
            make.bottom.equalTo(view)
            make.height.equalTo(49)
        }
        bar.buttonBackclosure = {[weak self](type: ComposeButtonType)->() in
            //辨别按钮
            switch type{
            case .Picture:
                printLog("Picture")
                self?.selectPhoto()
            case .Mention:
                printLog("Mention")
            case .Emoticon:
                printLog("Emoticon")
                self?.textView.EmoticonKeyboard()
            case .Trend:
                printLog("Trend")
            case .Add:
                printLog("Add")
            }
            
        }
    }
    
    private func selectPhoto(){
        let photoVc = UIImagePickerController()
        photoVc.sourceType = .PhotoLibrary
        photoVc.delegate = self
        presentViewController(photoVc, animated: true, completion: nil)
    }
    
    // MARK: - navigationButton响应事件
    @objc private func leftBarButtonClick(){

        self.dismissViewControllerAnimated(true, completion: nil)
        view.endEditing(true)
    
    }
    
    @objc private func rightBarButtonClick(){
        
        if photoPicker.imageList.count == 0{
            //纯文本微博
            HTTPClient.shareManager.postTextStatus(textView.oringinalStr) { (seccess) -> () in
                if !seccess {
                    SVProgressHUD.showErrorWithStatus("上传失败")
                }else{
                    SVProgressHUD.showSuccessWithStatus("上传成功")
                    self.dismissViewControllerAnimated(true, completion: nil)
                }
            }
        }else{
            //带图片微博
            var datas = [NSData]()
            for photo in photoPicker.imageList{
                datas.append(UIImagePNGRepresentation(photo)!)
            }
            printLog(datas.count)
            //显示等待
            SVProgressHUD.show()
            HTTPClient.shareManager.postImageStatus(textView.oringinalStr, datas: datas, callBack: { (seccess) -> () in
                if !seccess {
                    SVProgressHUD.showErrorWithStatus("上传失败")
                }else{
                    SVProgressHUD.showSuccessWithStatus("上传成功")
                    self.dismissViewControllerAnimated(true, completion: nil)
                }
            })
            
        }
        
        self.view.endEditing(true)
        
    }
    
    // MARK: - 通知处理
    //bar随键盘的移动
    @objc private func keyboardChange(noti: NSNotification){
//        printLog(noti.userInfo!)
        if !textView.prepare{
            return
        }
        
        let keyboardFrame = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let duration = (noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        bar.snp_updateConstraints(closure: { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - kScreenHeight)
        })
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.bar.layoutIfNeeded()
        }
    }
    
    @objc private func emoticonNotificationDeal(noti: NSNotification){
        
        let emoticonButton = noti.object as! SCEmoticonButton
        
        textView.setAtrributeStringWithEmoticon(emoticonButton.emoticon!)
        
        //手动调用代理方法与发送通知
        NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
        textViewDidChange(textView)
    }
    
    @objc private func deleteNotificationDeal(){
        textView.deleteBackward()
    }
    
    //懒加载控件
    private lazy var titleview: UIView = SCComposeTitleView()
    private lazy var textView: SCTextView = SCTextView()
    private lazy var photoPicker: SCPhotoPickerView = SCPhotoPickerView()
    private lazy var bar: SCComposeBar = SCComposeBar(frame: CGRectZero)
    private lazy var rightBarItem: UIBarButtonItem = {
        
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: .Highlighted)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: .Disabled)
        btn.titleLabel?.font = UIFont.systemFontOfSize(14)
        btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
        btn.setTitle("发送", forState: .Normal)
        btn.frame.size = CGSize(width: 45, height: 30)
        btn.addTarget(self, action: "rightBarButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        let item = UIBarButtonItem()
        item.customView = btn
        return item
    }()
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

// MARK: - 图片选择
extension SCComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        self.navigationItem.rightBarButtonItem?.enabled = true
        //缩放图片
        let scaleImage = image.scaleImage(500/image.size.width < 1 ? 500/image.size.width : 1)
        photoPicker.addImage(scaleImage)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}

// MARK: - textView 的代理方法
extension SCComposeViewController: UITextViewDelegate{

    func textViewDidChange(textView: UITextView) {
        self.navigationItem.rightBarButtonItem?.enabled = textView.text.characters.count != 0
//        printLog(textView.contentSize)
        photoPicker.snp_updateConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(40 + textView.contentSize.height)
        }
        
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        view.endEditing(true)
    }
    
}

//可以用bounds代替
//class emoticonAttach: NSTextAttachment {
//    override func attachmentBoundsForTextContainer(textContainer: NSTextContainer?, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect {
//        return CGRect(x: 0, y: -3, width: lineFrag.height, height: lineFrag.height)
//    }
//}

